<script lang="ts" setup>
import { ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'
import { GetCodeData, PostCreateCode } from '@/api/modules/screenCode'
import GetCacheData from '@/store/modules/NewPageCache'

// const imgDomain = 'https://img1.eprhan.cc'
const cacheData = GetCacheData()

let PageNum = cacheData.GetCacheData('screenCodeList').currentPage

const total = ref(0)
const findFrom = ref({
  ...(cacheData.GetCacheData('screenCodeList').fromData),
})
const dataList: any = reactive({
  list: [],
})
const loading = ref(true)

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.ExCode && ({ ExCode: findFrom.value.ExCode })),
    ...(findFrom.value.UserId && ({ UserId: findFrom.value.UserId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...(findFrom.value.Status !== '~' && ({ Status: findFrom.value.Status })),
    ...(findFrom.value.Time.length !== 0 && ({ AssignTimeStart: findFrom.value.Time[0], AssignTimeEnd: findFrom.value.Time[1] })),
  }
  await GetCodeData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList()
  cacheData.SetCacheData('screenCodeList', 1, 20, findFrom.value)
}

const dialogVisible = ref(false)

const parsedData = ref<string[]>([])

function BatchAdd() {
  dialogVisible.value = true
}

async function handleFileChange(file: any) {
  parsedData.value = [] // 清空之前的数据

  try {
    if (file.raw.type.includes('text/') || file.name.endsWith('.txt')) {
      await parseTxtFile(file.raw)
    }
    else if (
      file.name.endsWith('.xlsx')
      || file.name.endsWith('.xls')
      || file.name.endsWith('.csv')
      || file.raw.type.includes('spreadsheet')
    ) {
      await parseExcelFile(file.raw)
    }
    else {
      ElMessage.error('不支持的文件格式')
    }
  }
  catch (error) {
    console.error('解析文件出错:', error)
    ElMessage.error('文件解析失败')
  }
}

// 解析TXT文件
function parseTxtFile(file: File): Promise<void> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = (e: ProgressEvent<FileReader>) => {
      const content = e.target?.result as string
      if (!content) {
        reject(new Error('文件内容为空'))
        return
      }

      // 使用多种分隔符分割文本
      const separators = /[,，.。;；\s]+/
      const items = content.split(separators)
        .map((item: string) => item.trim())
        .filter((item: string) => item.length > 0)

      parsedData.value = items
      ElMessage.success(`成功解析 ${items.length} 条数据`)
      resolve()
    }

    reader.onerror = () => {
      reject(new Error('读取文件失败'))
    }

    reader.readAsText(file)
  })
}

// 解析Excel文件
function parseExcelFile(file: File): Promise<void> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = (e: ProgressEvent<FileReader>) => {
      try {
        if (!e.target?.result) {
          reject(new Error('文件内容为空'))
          return
        }

        const data = new Uint8Array(e.target.result as ArrayBuffer)
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]]

        // 将工作表转换为JSON数组
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 }) as unknown[][]

        // 提取所有单元格数据并扁平化为一维数组
        const items = jsonData
          .flat()
          .map((item: unknown) => String(item).trim())
          .filter((item: string) => item.length > 0)

        parsedData.value = items
        ElMessage.success(`成功解析 ${items.length} 条数据`)
        resolve()
      }
      catch (error) {
        reject(error)
      }
    }

    reader.onerror = () => {
      reject(new Error('读取文件失败'))
    }

    reader.readAsArrayBuffer(file)
  })
}

function Cancel() {
  parsedData.value = []
  dialogVisible.value = false
}

function SetCode() {
  if (parsedData.value.length === 0) {
    ElMessage.error('请先上传文件')
    return
  }
  // console.log(parsedData.value)

  PostCreateCode(parsedData.value).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success(`添加成功，新增${res.data}条`)
      dialogVisible.value = false
      GetDataList()
    }
    else {
      if (typeof res.errors === 'string') {
        ElMessage.error(`添加失败。${res.errors}`)
      }
      else {
        let errorStr = ''
        for (const key in res.errors) {
          errorStr += `${key}：${res.errors[key]}；`
        }
        ElMessage.error(`添加失败。${errorStr}`)
      }
    }
  })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('screenCodeList', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('screenCodeList').currentSize)
  cacheData.SetCacheData('screenCodeList', val, cacheData.GetCacheData('screenCodeList').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('screenCodeList').currentPage || 1
})

onMounted(async () => {
  try {
    await GetDataList(cacheData.GetCacheData('screenCodeList').currentPage, cacheData.GetCacheData('screenCodeList').currentSize)
  }
  catch (error) {
    console.error('Error fetching data:', error)
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="兑换码">
                <el-input v-model="findFrom.ExCode" placeholder="请输入兑换码" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="用户ID">
                <el-input v-model="findFrom.UserId" placeholder="请输入用户ID" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="授权手机号">
                <el-input v-model="findFrom.UserPhone" placeholder="请输入授权手机号" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="findFrom.Status" placeholder="请选择状态">
                  <el-option label="全部" value="~" />
                  <el-option label="未分配" :value="0" />
                  <el-option label="已分配" :value="1" />
                  <el-option label="已兑换" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="分配时间">
                <el-date-picker
                  v-model="findFrom.Time"
                  type="daterange"
                  range-separator="到"
                  start-placeholder="分配开始时间"
                  end-placeholder="分配结束时间"
                />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="BatchAdd">
          批量添加兑换码
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="兑换码ID" width="120" />
        <el-table-column align="center" prop="exCode" label="兑换码" width="120" />
        <el-table-column align="center" prop="status" label="状态" width="160">
          <template #default="scope">
            <el-tag>
              {{ scope.row.status === 0 ? '未分配'
                : scope.row.status === 1 ? '已分配'
                  : scope.row.status === 2 ? '已兑换' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="subscriber.userId" label="用户ID" width="100" />
        <el-table-column align="center" prop="subscriber" label="用户信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.subscriber || scope.row.subscriber.userId === 0">
              未授权
            </div>
            <el-tooltip
              v-else
              class="box-item"
              effect="dark"
              :content="scope.row.subscriber?.scOpenId"
              placement="top"
            >
              <div class="user-name">
                <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriber?.userAvatar" />
                <div>
                  <p style="margin: 0;">
                    {{ scope.row.subscriber?.userNickName }}
                  </p>
                  <span>
                    {{ scope.row.subscriber?.userPhone }}
                  </span>
                </div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="desp" label="描述" min-width="350" />
        <el-table-column align="center" prop="assignTime" label="分配时间" width="200" />
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="修改时间" width="200" />
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('screenCodeList').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>

    <el-dialog
      v-model="dialogVisible"
      title=""
      width="500"
    >
      <el-upload
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        accept=".txt,.xlsx,.xls,.csv"
        :show-file-list="false"
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">
          拖放文件到此处或<em>点击上传</em>
        </div>
        <div class="el-upload__tip">
          支持 TXT、Excel 文件（.txt, .xlsx, .xls, .csv）
        </div>
      </el-upload>
      <div v-if="parsedData.length > 0" class="result-container">
        <h3>解析结果：</h3>
        <el-tag
          v-for="(item, index) in parsedData"
          :key="index"
          class="result-tag"
        >
          {{ item }}
        </el-tag>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Cancel">
            取消
          </el-button>
          <el-button type="primary" @click="SetCode">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.result-tag {
  margin-right: 5px;
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}
</style>
